import React, { useState, useRef, useEffect } from 'react'
import ReactMarkdown from 'react-markdown'
import { useChatStore } from '../stores/chatStore'
import { useAuthStore } from '../stores/authStore'
import { aiService, ChatMessage as AIChatMessage, AIModel } from '../services/aiService'
import { wsService, WSMessage } from '../services/websocketService'
import { Button } from './ui/Button'
import { AIAvatar, UserAvatar } from './ui/Avatar'
import { InputBox } from './ui/InputBox'
import { AISearchButton, AIReadButton, AIWriteButton, AIImageButton } from './ui/FunctionButton'
import { CompactModelSelector } from './ui/ModelSelector'
import { BrainIcon, SendIcon } from './ui/Icon'
import { RoleType } from './ui/RoleSelector'

interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
  isPinned?: boolean
}

interface ChatProps {
  showSettings: boolean
  setShowSettings: (show: boolean) => void
  logout: () => void
  currentRole: RoleType
  currentRoleInfo?: {
    name: string
    icon?: string
    systemPrompt?: string
  }
}

export const Chat: React.FC<ChatProps> = ({ showSettings, setShowSettings, logout, currentRole, currentRoleInfo }) => {
  const [input, setInput] = useState('')
  // 根据角色生成欢迎消息
  const getWelcomeMessage = (roleId: RoleType) => {
    const welcomeMessages = {
      emma: '你好！我是Emma，一位温暖的心理咨询师。我很高兴能为你提供情绪支持和心理疏导。请放心和我分享你的感受，我会认真倾听并帮助你。',
      sophie: '你好！我是Sophie，你的学术研究助理。我可以帮助你进行论文写作、文献综述、研究方法指导等学术工作。请告诉我你需要什么帮助。',
      mike: '你好！我是Mike，一位资深的面试教练和HR总监。我可以帮你准备面试、优化简历、制定职业规划。我们直接开始吧，有什么问题尽管问！'
    }
    
    // 对于自定义角色，使用角色名称生成欢迎消息
    if (currentRoleInfo && currentRoleInfo.name) {
      return `你好！我是${currentRoleInfo.name}。请问有什么我可以帮助你的吗？`
    }
    
    return welcomeMessages[roleId] || '你好！我是MindMate，你的AI学习伙伴。请问有什么我可以帮助你的吗？'
  }

  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      role: 'assistant',
      content: getWelcomeMessage(currentRole),
      timestamp: new Date()
    }
  ])
  const [isLoading, setIsLoading] = useState(false)
  const [availableModels, setAvailableModels] = useState<AIModel[]>([])
  const [currentModel, setCurrentModel] = useState<string>('llama-3.1-70b-versatile')
  const [aiStatus, setAiStatus] = useState<any>(null)
  const [wsConnected, setWsConnected] = useState(false)
  const [streamingMessage, setStreamingMessage] = useState<string>('')
  const [currentAIMessageId, setCurrentAIMessageId] = useState<string | null>(null)
  const [searchEnabled, setSearchEnabled] = useState(false)
  const [currentSearchResults, setCurrentSearchResults] = useState<any[]>([])  // 真实搜索结果
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const messagesContainerRef = useRef<HTMLDivElement>(null)
  const { user } = useAuthStore()

  // 监听角色变化，更新欢迎消息
  useEffect(() => {
    setMessages([
      {
        id: '1',
        role: 'assistant',
        content: getWelcomeMessage(currentRole),
        timestamp: new Date()
      }
    ])
  }, [currentRole])

  // Pin消息处理函数
  const togglePinMessage = (messageId: string) => {
    setMessages(prev => prev.map(msg => 
      msg.id === messageId 
        ? { ...msg, isPinned: !msg.isPinned }
        : msg
    ))
  }

  // 复制消息内容
  const copyMessage = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content)
      // TODO: 添加复制成功提示
      console.log('消息已复制到剪贴板')
    } catch (error) {
      console.error('复制失败:', error)
    }
  }

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  // 处理滚动位置
  useEffect(() => {
    if (messages.length > 1) {
      // 有多条消息时，滚动到底部
      scrollToBottom()
    } else {
      // 只有一条欢迎消息时，确保滚动到顶部
      if (messagesContainerRef.current) {
        messagesContainerRef.current.scrollTop = 0
      }
    }
  }, [messages])

  // 初始化AI服务和WebSocket
  useEffect(() => {
    const initializeServices = async () => {
      try {
        // 获取可用模型
        const modelsData = await aiService.getAvailableModels()
        setAvailableModels(modelsData.models)
        setCurrentModel(modelsData.default)

        // 检查API状态
        const status = await aiService.checkAPIStatus()
        setAiStatus(status)

        console.log('AI服务初始化完成:', { models: modelsData.models.length, status })

        // 演示版不使用WebSocket
        console.log('演示版使用REST API模式')
      } catch (error) {
        console.error('服务初始化失败:', error)
      }
    }

    initializeServices()

    // 演示版不使用WebSocket事件监听
    setWsConnected(false) // 演示版始终显示未连接状态
    
    // 清理函数（空）
    return () => {
      console.log('演示版清理')
    }
  }, [])

  // WebSocket消息处理
  const handleWSMessage = (wsMessage: WSMessage) => {
    console.log('处理WebSocket消息:', wsMessage)
    
    switch (wsMessage.type) {
      case 'system':
        // 系统消息，可以显示连接状态等
        console.log('系统消息:', wsMessage.message)
        break
        
      case 'message_received':
        // 确认收到用户消息
        console.log('服务器确认收到消息:', wsMessage.user_message)
        break
        
      case 'ai_start':
        // AI开始回复，创建新的AI消息
        const aiMessageId = Date.now().toString()
        setCurrentAIMessageId(aiMessageId)
        setStreamingMessage('')
        
        const newAIMessage: Message = {
          id: aiMessageId,
          role: 'assistant',
          content: '',
          timestamp: new Date()
        }
        setMessages(prev => [...prev, newAIMessage])
        break
        
      case 'ai_chunk':
        // AI流式回复片段
        if (wsMessage.chunk && currentAIMessageId) {
          setStreamingMessage(wsMessage.full_message || '')
          // 更新当前AI消息的内容
          setMessages(prev => prev.map(msg => 
            msg.id === currentAIMessageId 
              ? { ...msg, content: wsMessage.full_message || '' }
              : msg
          ))
        }
        break
        
      case 'ai_end':
        // AI回复结束
        if (wsMessage.final_message && currentAIMessageId) {
          setMessages(prev => prev.map(msg => 
            msg.id === currentAIMessageId 
              ? { ...msg, content: wsMessage.final_message || '' }
              : msg
          ))
        }
        setCurrentAIMessageId(null)
        setStreamingMessage('')
        setIsLoading(false)
        break
        
      case 'pong':
        // 心跳回复
        console.log('收到心跳回复')
        break
        
      default:
        console.log('未处理的WebSocket消息类型:', wsMessage.type)
    }
  }

  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault()
    if (!input.trim() || isLoading) return

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: input.trim(),
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    const messageContent = input.trim()
    setInput('')
    setIsLoading(true)

    // 演示版直接使用REST API，不使用WebSocket
    console.log('使用REST API发送消息')
    await fallbackToRestAPI(messageContent)
  }

  // REST API 回退方法
  const fallbackToRestAPI = async (messageContent: string) => {
    try {
      // 构建包含角色信息的对话历史
      const chatHistory: AIChatMessage[] = []
      
      // 添加角色的system prompt
      if (currentRoleInfo?.systemPrompt) {
        chatHistory.push({
          role: 'system',
          content: currentRoleInfo.systemPrompt
        })
      }
      
      // 添加历史消息
      messages.forEach(msg => {
        if (msg.role !== 'system') { // 避免重复添加system消息
          chatHistory.push({
            role: msg.role,
            content: msg.content
          })
        }
      })
      
      // 添加当前用户消息
      chatHistory.push({
        role: 'user',
        content: messageContent
      })

      // 发送到AI服务（包含角色参数和搜索增强）
      const aiResponse = await aiService.sendMessage({
        messages: chatHistory,
        model: currentRoleInfo?.modelConfig?.model || currentModel,
        temperature: currentRoleInfo?.modelConfig?.temperature || 0.7,
        max_tokens: currentRoleInfo?.modelConfig?.maxTokens || 1500,
        search_enabled: searchEnabled  // 传递搜索增强状态
      })

      // 更新搜索结果
      if (aiResponse.search_results) {
        setCurrentSearchResults(aiResponse.search_results)
        console.log('搜索结果已更新:', aiResponse.search_results.length, '个结果')
      } else {
        setCurrentSearchResults([])
      }

      // 创建AI回复消息
      const aiMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: aiResponse.content,
        timestamp: new Date()
      }
      
      setMessages(prev => [...prev, aiMessage])
      setIsLoading(false)

    } catch (error) {
      console.error('AI服务错误:', error)
      
      // 错误处理
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: `抱歉，我暂时无法回应。请检查网络连接或稍后再试。\n\n技术详情：${error}`,
        timestamp: new Date()
      }
      
      setMessages(prev => [...prev, errorMessage])
      setIsLoading(false)
    }
  }

  return (
    <div className="flex flex-col h-full" style={{ background: 'var(--gray-50)' }}>
      {/* 对话头部 */}
      <div className="bg-white border-b border-gray-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <h2 style={{ fontSize: 'var(--text-lg)', fontWeight: 600 }}>
              新对话
            </h2>
            {/* 当前角色指示器 */}
            <div className="flex items-center gap-2 px-3 py-1.5 bg-blue-50 border border-blue-200 rounded-full">
              <span className="text-sm">{currentRoleInfo?.icon || '🤖'}</span>
              <span className="text-sm font-medium text-blue-700">
                {currentRoleInfo?.name || 'AI助手'}
              </span>
              <span className="text-xs text-blue-500 bg-blue-100 px-1.5 py-0.5 rounded-full">
                激活中
              </span>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button className="p-2 hover:bg-gray-100 rounded-lg transition-colors" title="导出对话">
              📥
            </button>
            <button className="p-2 hover:bg-gray-100 rounded-lg transition-colors" title="清空对话">
              🗑️
            </button>
          </div>
        </div>
      </div>

      {/* 消息区域 */}
      <div 
        ref={messagesContainerRef}
        className="chat-messages-container custom-scrollbar"
      >
        {/* 搜索结果展示区域 */}
        {searchEnabled && currentSearchResults.length > 0 && (
          <div className="p-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
            <div className="mb-4 flex items-center gap-2">
              <span className="text-lg">🔍</span>
              <h3 style={{ fontSize: 'var(--text-lg)', fontWeight: 600, color: 'var(--primary-700)' }}>
                搜索增强结果
              </h3>
              <span className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full">
                {currentSearchResults.length} 个结果
              </span>
            </div>
            
            <div className="grid gap-3">
              {currentSearchResults.map((result, index) => (
                <div 
                  key={index}
                  className="bg-white p-4 rounded-lg border border-blue-200 hover:border-blue-300 transition-all hover:shadow-md cursor-pointer"
                  style={{ borderRadius: 'var(--radius-lg)' }}
                >
                  <div className="flex items-start gap-3">
                    <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
                      <span className="text-sm">🌐</span>
                    </div>
                    <div className="flex-1 min-w-0">
                      <h4 className="font-medium text-gray-900 mb-1 line-clamp-1" style={{ fontSize: 'var(--text-sm)' }}>
                        {result.title || '搜索结果'}
                      </h4>
                      <p className="text-gray-600 text-sm line-clamp-2 mb-2">
                        {result.snippet || result.body || '暂无摘要'}
                      </p>
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <span>{result.source || 'DuckDuckGo'}</span>
                        <span>•</span>
                        <a href={result.url} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                          查看原文
                        </a>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            
            <div className="mt-4 text-center">
              <button className="text-sm text-blue-600 hover:text-blue-700 hover:underline transition-colors">
                查看更多搜索结果
              </button>
            </div>
          </div>
        )}

        {/* 欢迎界面 - 当没有消息时显示 */}
        {messages.length <= 1 && (
          <div className="flex items-center justify-center h-full px-6">
            <div className="max-w-2xl mx-auto text-center space-y-6 -mt-8">
              <div className="w-16 h-16 mx-auto bg-gradient-to-r from-blue-500 to-blue-600 rounded-2xl flex items-center justify-center shadow-lg">
                <span className="text-2xl">🧠</span>
              </div>
              <div>
                <h2 className="text-2xl font-bold text-neutral-900 mb-2">
                  Hi~ 我是MindMate，您的AI学习伙伴
                </h2>
                <p className="text-neutral-600 leading-relaxed">
                  可以为您答疑解惑、精读文档、创意写作、让工作更松工作，多点生活
                </p>
              </div>
            </div>
          </div>
        )}
        
        {/* 对话消息 */}
        {messages.length > 1 && (
          <div className="flex-1 p-6 space-y-6 overflow-y-auto">
            {messages.map((message, index) => (
              <div key={message.id} className={`flex gap-4 group message-fade-in relative ${message.isPinned ? 'ring-2 ring-yellow-200 bg-yellow-50/30 rounded-xl p-2' : ''}`}>
                {/* 固定消息标识 */}
                {message.isPinned && (
                  <div className="absolute -top-2 -right-2 w-6 h-6 bg-yellow-400 text-white rounded-full flex items-center justify-center text-xs z-10 shadow-md">
                    📌
                  </div>
                )}
                {/* AI消息布局 */}
                {message.role === 'assistant' && (
                  <>
                    {/* AI头像 - 优化橙色渐变 */}
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 shadow-md hover:shadow-lg transition-all" style={{
                      background: 'linear-gradient(135deg, var(--accent-500) 0%, var(--accent-600) 100%)',
                      color: 'white',
                      fontSize: '16px',
                      boxShadow: '0 2px 6px rgba(249, 115, 22, 0.25)'
                    }}>
                      🤖
                    </div>
                    
                    {/* AI消息内容 */}
                    <div className="flex-1 max-w-4xl">
                      <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-md hover:shadow-lg message-hover-lift transition-all" style={{
                        borderRadius: 'var(--radius-xl)',
                        fontSize: 'var(--text-base)',
                        lineHeight: 1.6,
                        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)'
                      }}>
                        <div className="prose prose-sm max-w-none prose-headings:text-gray-900 prose-headings:font-semibold prose-p:text-gray-700 prose-p:leading-relaxed prose-strong:text-gray-900 prose-code:text-blue-600 prose-code:bg-blue-50 prose-code:px-1 prose-code:py-0.5 prose-code:rounded prose-pre:bg-gray-50 prose-pre:border prose-li:text-gray-700">
                          <ReactMarkdown
                            components={{
                              // 自定义段落样式
                              p: ({children}) => <p className="mb-4 last:mb-0">{children}</p>,
                              // 自定义标题样式
                              h1: ({children}) => <h1 className="text-xl font-bold mb-4 text-gray-900">{children}</h1>,
                              h2: ({children}) => <h2 className="text-lg font-semibold mb-3 text-gray-800">{children}</h2>,
                              h3: ({children}) => <h3 className="text-base font-semibold mb-2 text-gray-800">{children}</h3>,
                              // 自定义列表样式
                              ul: ({children}) => <ul className="mb-4 space-y-1 pl-4">{children}</ul>,
                              ol: ({children}) => <ol className="mb-4 space-y-1 pl-4">{children}</ol>,
                              li: ({children}) => <li className="text-gray-700">{children}</li>,
                              // 自定义代码块样式
                              pre: ({children}) => <pre className="mb-4 p-3 bg-gray-50 rounded-lg border overflow-x-auto">{children}</pre>,
                              code: ({children, className}) => {
                                const isInline = !className;
                                return isInline ? 
                                  <code className="px-1 py-0.5 bg-blue-50 text-blue-600 rounded text-sm font-mono">{children}</code> :
                                  <code className={className}>{children}</code>
                              },
                              // 自定义引用样式
                              blockquote: ({children}) => <blockquote className="mb-4 pl-4 border-l-4 border-blue-200 bg-blue-50 p-3 rounded-r-lg">{children}</blockquote>,
                              // 自定义强调样式
                              strong: ({children}) => <strong className="font-semibold text-gray-900">{children}</strong>,
                              em: ({children}) => <em className="italic text-gray-700">{children}</em>
                            }}
                          >
                            {message.content}
                          </ReactMarkdown>
                        </div>
                      </div>
                      
                      {/* 操作按钮 - hover时显示，优化样式 */}
                      <div className="flex gap-3 mt-3 opacity-0 group-hover:opacity-100 transition-all duration-300">
                        <button 
                          onClick={() => copyMessage(message.content)}
                          className="flex items-center gap-2 px-3 py-2 bg-white border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 hover:scale-[1.02] transition-all duration-200 shadow-sm"
                          style={{
                            borderRadius: 'var(--radius-md)',
                            fontSize: 'var(--text-xs)'
                          }}
                          title="复制消息"
                        >
                          <span>📋</span>
                          <span>复制</span>
                        </button>
                        <button 
                          className="flex items-center gap-2 px-3 py-2 bg-white border border-gray-200 rounded-lg hover:border-orange-300 hover:bg-orange-50 hover:scale-[1.02] transition-all duration-200 shadow-sm"
                          style={{
                            borderRadius: 'var(--radius-md)',
                            fontSize: 'var(--text-xs)'
                          }}
                          title="重新生成回答"
                        >
                          <span>🔄</span>
                          <span>重新生成</span>
                        </button>
                        <button 
                          onClick={() => togglePinMessage(message.id)}
                          className={`flex items-center gap-2 px-3 py-2 bg-white border rounded-lg hover:scale-[1.02] transition-all duration-200 shadow-sm ${
                            message.isPinned 
                              ? 'border-yellow-300 bg-yellow-50 text-yellow-700' 
                              : 'border-gray-200 hover:border-yellow-300 hover:bg-yellow-50'
                          }`}
                          style={{
                            borderRadius: 'var(--radius-md)',
                            fontSize: 'var(--text-xs)'
                          }}
                          title={message.isPinned ? "取消固定" : "固定消息"}
                        >
                          <span>{message.isPinned ? '📌' : '📌'}</span>
                          <span>{message.isPinned ? '已固定' : '固定'}</span>
                        </button>
                      </div>
                    </div>
                  </>
                )}

                {/* 用户消息布局 */}
                {message.role === 'user' && (
                  <div className="flex justify-end w-full">
                    <div className="flex gap-3 max-w-2xl">
                      {/* 用户消息内容 */}
                      <div className="p-5 rounded-xl text-white shadow-md hover:shadow-lg transition-all" style={{
                        background: 'var(--primary-600)',
                        borderRadius: 'var(--radius-xl)',
                        fontSize: 'var(--text-base)',
                        lineHeight: 1.6,
                        boxShadow: '0 2px 8px rgba(59, 130, 246, 0.2)'
                      }}>
                        <div className="prose prose-sm max-w-none prose-p:text-white prose-strong:text-white prose-em:text-gray-100">
                          <ReactMarkdown
                            components={{
                              p: ({children}) => <p className="mb-2 last:mb-0">{children}</p>,
                              strong: ({children}) => <strong className="font-semibold text-white">{children}</strong>,
                              em: ({children}) => <em className="italic text-gray-100">{children}</em>,
                              code: ({children}) => <code className="px-1 py-0.5 bg-white bg-opacity-20 rounded text-sm font-mono">{children}</code>
                            }}
                          >
                            {message.content}
                          </ReactMarkdown>
                        </div>
                      </div>
                      
                      {/* 用户头像 */}
                      <div className="w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 text-sm font-medium" style={{
                        background: 'var(--primary-100)',
                        color: 'var(--primary-700)'
                      }}>
                        {user?.username?.charAt(0) || 'U'}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {/* AI思考指示器 */}
        {isLoading && (
          <div className="flex gap-3 p-6">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 shadow-md" style={{
              background: 'linear-gradient(135deg, var(--accent-500) 0%, var(--accent-600) 100%)',
              color: 'white',
              fontSize: '16px',
              boxShadow: '0 2px 6px rgba(249, 115, 22, 0.25)'
            }}>
              🤖
            </div>
            <div className="flex-1">
              <div className="bg-white p-4 rounded-xl border border-gray-100 shadow-md" style={{
                borderRadius: 'var(--radius-xl)',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)'
              }}>
                <div className="flex items-center gap-2">
                  <div className="flex gap-1">
                    <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '0ms' }}></div>
                    <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '150ms' }}></div>
                    <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '300ms' }}></div>
                  </div>
                  <span style={{ fontSize: 'var(--text-sm)', color: 'var(--gray-500)' }}>
                    {currentRoleInfo?.name || 'AI助手'}正在思考...
                  </span>
                </div>
              </div>
            </div>
          </div>
        )}
        
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="bg-white border-t p-5" style={{ borderColor: 'var(--gray-200)' }}>
        <div className="flex gap-3 items-end">
          {/* 输入框区域 */}
          <div className="flex-1 bg-gray-50 border-2 input-focus-glow transition-all shadow-sm hover:shadow-md" style={{
            backgroundColor: 'var(--gray-50)',
            border: '2px solid var(--gray-200)',
            borderRadius: '20px',
            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.02)'
          }}>
            <textarea 
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyPress={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault()
                  handleSubmit()
                }
              }}
              disabled={isLoading}
              className="w-full p-3 bg-transparent outline-none resize-none"
              style={{
                fontSize: 'var(--text-base)',
                minHeight: '44px',
                maxHeight: '120px'
              }}
              placeholder="输入你的问题..."
              rows={1}
            />
            
            {/* 底部工具栏 */}
            <div className="flex items-center justify-between px-3 pb-3 gap-3">
              <div className="flex items-center gap-2">
                <button 
                  className="p-1.5 hover:bg-gray-200 rounded-lg transition-colors"
                  title="上传文件"
                  style={{ borderRadius: 'var(--radius-md)' }}
                >
                  📎
                </button>
              </div>
              
              {/* 搜索功能开关 */}
              <div className="flex items-center gap-2">
                <label className="flex items-center gap-2 text-xs cursor-pointer" style={{ color: 'var(--gray-600)' }}>
                  <input
                    type="checkbox"
                    checked={searchEnabled}
                    onChange={(e) => setSearchEnabled(e.target.checked)}
                    className="w-3 h-3 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="flex items-center gap-1">
                    <span>🔍</span>
                    <span>启用搜索增强</span>
                  </span>
                </label>
              </div>
            </div>
          </div>
          
          {/* 发送按钮 */}
          <button 
            onClick={handleSubmit}
            disabled={isLoading || !input.trim()}
            className="w-12 h-12 text-white rounded-xl button-click-scale transition-all disabled:opacity-50 disabled:cursor-not-allowed glow-on-hover"
            style={{
              background: 'var(--primary-500)',
              borderRadius: 'var(--radius-lg)'
            }}
            onMouseEnter={(e) => {
              if (!isLoading && input.trim()) {
                e.currentTarget.style.background = 'var(--primary-600)'
              }
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'var(--primary-500)'
            }}
          >
            ➤
          </button>
        </div>
      </div>
    </div>
  )
}